﻿/// Copyright © 2013 Microsoft Corporation. 
/// This project is released under the Microsoft Public License (MS-PL)
///
namespace DataMorph.Web
{
    using System;
    using System.Net.Http;
    using System.Web.Http.Controllers;
    using System.Web.Http.Dispatcher;

    using Microsoft.Practices.Unity;

    public class CompositionRoot : IHttpControllerActivator
    {
        private readonly IUnityContainer container;

        public CompositionRoot(IUnityContainer container)
        {
            this.container = container;
        }

        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            try
            {
                var controller = (IHttpController)this.container.Resolve(controllerType);
                request.RegisterForDispose(new Disposer(() => this.container.Teardown(controller)));

                return controller;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}